﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using ObjectModel.PowerPoint.Events;

namespace ObjectModel.PowerPoint
{
    public class ObservableShape : ObservableObject
    {
        CachedObject mShape;
        SlideEvents mEvents;
        
        float mTop;
        float mLeft;
        float mHeight;
        float mWidth;

        public ObservableShape() { } // Parameterless constructor needed for serialization.

        public ObservableShape(Ppt.Shape shape)
        {
            CachedShape = new CachedObject(shape);
        }

        public CachedObject CachedShape
        {
            get
            {
                return mShape;
            }

            set
            {
                mShape = value;
                mEvents = Shape.GetSlide().GetEvents();
                mEvents.RegisterObserver(this);

                CaptureState();
            }
        }

        [XmlIgnore]
        public Ppt.Shape Shape { get { return Resolve() as Ppt.Shape; } }
        
        public override object Resolve()
        {
            return CachedShape.Resolve();
        }

        public override void Restore()
        {
            Shape.Top = mTop;
            Shape.Left = mTop;
            Shape.Height = mHeight;
            Shape.Width = mWidth;
        }

        public override void OnDeleted()
        {
            base.OnDeleted();

            mEvents.RemoveObserver(this);
        }

        public override void OnDeselected()
        {
            base.OnDeselected();
            
            if (Shape.Top != mTop || Shape.Left != mLeft)
                OnChanged(Events.ChangeType.Moved);

            if (Shape.Height != mHeight || Shape.Width != mWidth)
                OnChanged(Events.ChangeType.Resized);
        }
        
        public override void OnSelected()
        {
            base.OnSelected();
            CaptureState();
        }

        void CaptureState()
        {
            mTop = Shape.Top;
            mLeft = Shape.Left;
            mHeight = Shape.Height;
            mWidth = Shape.Width;
        }
    }
}
